package com.mh.nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author meng.han
 * @since 2021-11-16
 */
public class NioServer {

    public static void main(String[] args) throws IOException, InterruptedException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        serverSocketChannel.bind(new InetSocketAddress(9999));
        // 通道默认为阻塞的，这里设置为非阻塞的
        serverSocketChannel.configureBlocking(false);
        System.out.println("服务端启动完成...");
        while (true) {
            // 这里检查有没有客户端连接，因为这里是非阻塞的，所以如果没有客户端连接会返回null
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel == null) {
                System.out.println("没有客户端连接...");
                Thread.sleep(2000);
                continue;
            }
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int len = socketChannel.read(byteBuffer);
            System.out.println("接收到的客户端消息：" + new String(byteBuffer.array(), 0, len, StandardCharsets.UTF_8));
            socketChannel.write(ByteBuffer.wrap("不去".getBytes(StandardCharsets.UTF_8)));
            socketChannel.close();
        }


    }

}
